package com.chenjiagou.controller;

import com.chenjiagou.pojo.User;
import com.chenjiagou.service.LoginService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Optional;
import java.util.List;
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private com.chenjiagou.feign.NotificationFeignClient notificationFeignClient;

    @GetMapping("/login")
    public String showLogin() {
        return "login"; // 返回 Thymeleaf 模板名
    }
    @GetMapping("/index")
    public String home() {
        return "index"; // 返回 templates/index.html 页面
    }




    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        Model model) {
        User user = loginService.login(username, password);
        if (user != null) {
            session.setAttribute("userId", user.getId());
            session.setAttribute("role", user.getRole());

            // 如果是管理员，跳转至管理员主页
            if (user.getRole() == 1) {
                return "redirect:/admin/home";
            }

            // 普通用户跳转主页
            Integer unreadCount = Optional.ofNullable(notificationFeignClient.findUnreadByUserId(user.getId()))
                    .map(List::size)
                    .orElse(0);
            model.addAttribute("unreadCount", unreadCount);
            
            return "index";
        } else {
            model.addAttribute("error", "用户名、密码错误 或 账号已被禁用");
            return "login";
        }
    }


}
